package cn.ihoway.game;

import cn.ihoway.annotation.Processor;
import cn.ihoway.common.CommonProcessor;
import cn.ihoway.entity.Allocation;
import cn.ihoway.entity.Room;
import cn.ihoway.game.io.PlayerChatInput;
import cn.ihoway.game.io.PlayerChatOutput;
import cn.ihoway.redis.AllocationRedis;
import cn.ihoway.redis.CharacterRedis;
import cn.ihoway.redis.RoomRedis;
import cn.ihoway.socket.GameSessionManager;
import cn.ihoway.type.NotifyType;
import cn.ihoway.type.StatusCode;
import cn.ihoway.util.HowayLog;
import cn.ihoway.util.HowayMessage;
import cn.ihoway.util.HowayWsResult;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.ArrayList;

/**
 * 玩家发言
 */
@Processor(name = "PlayerChatProcessor")
public class PlayerChatProcessor  extends CommonProcessor<PlayerChatInput, PlayerChatOutput> {
    private final HowayLog logger = new HowayLog(PlayerChatProcessor.class);
    private final AllocationRedis allocationRedis = new AllocationRedis();
    private final CharacterRedis characterRedis = new CharacterRedis();
    private final RoomRedis roomRedis = new RoomRedis();

    @Override
    protected StatusCode dataCheck(PlayerChatInput input){
        return StatusCode.SUCCESS;
    }
    
    @Override
    protected HowayWsResult process(PlayerChatInput input, PlayerChatOutput output) throws IOException {
        Allocation allocation = allocationRedis.getBySessionId(input.inChomm.sessionId);
        if(allocation == null){
            return HowayWsResult.createFailResult(StatusCode.ROOM_EMPTY,output);
        }
        String roomId = allocation.getRoomId();
        Room room = roomRedis.get(roomId);

        String name = "";
        //游戏开始用游戏角色发言
        if(room.getStatus() == 2){
            name = characterRedis.get(allocation.getCharacterId()).getName();
        }else {
            name = input.inChomm.sessionId;
        }
        ArrayList<WebSocketSession> sessions = GameSessionManager.getFromRoom(roomId);
        for (WebSocketSession session : sessions){
            String sessonId = session.getAttributes().get("session_id").toString();
            if(!input.inChomm.sessionId.equals(sessonId)){
                HowayMessage message = new HowayMessage(NotifyType.THEIRS,input.inChomm.content);
                message.setSender(name);
                session.sendMessage(new TextMessage(message.toString()));
            }
        }
        return HowayWsResult.createSuccessResult(output);
    }
}